<template>
  <div class="d_mainFlex">
    <div class="d_treeBox p10">
      <el-form
        ref="materForm"
        :model="form"
        :rules="rules"
        hide-required-asterisk
        label-width="auto"
        class="dialogForm dialogInlineForm"
        label-position="top"
      >
        <el-row>
          <el-col>
            <el-form-item label="操作人员">
              <div class="flex">
                <el-input
                  v-model="name"
                  size="small"
                  placeholder="输入工号或扫码"
                  disabled
                />
                <el-button
                  size="small"
                  type="primary"
                  style="margin-left: 5px; min-width: 70px"
                  @click="loginModel = true"
                  >切换</el-button
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="生产单号" prop="produceTaskBillNo">
              <el-input
                v-model="form.produceTaskBillNoLl"
                size="small"
                ref="produceTaskBillNo"
                @keyup.enter.native="handleSave()"
                placeholder="输入生产单号或扫码"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-button
              type="primary"
              size="small"
              style="width: 100%; margin-top: 10px"
              @click.native.prevent="handleSave()"
              >生产领料</el-button
            >
          </el-col>
          <!-- <el-col>
            <el-form-item label="生产单号" prop="produceTaskBillNo">
              <el-input
                v-model="form.produceTaskBillNoFl"
                size="small"
                ref="produceTaskBillNo"
                @keyup.enter.native="handleSave(2)"
                placeholder="输入生产单号或扫码"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-button
              type="primary"
              size="small"
              style="width: 100%; margin-top: 10px"
              @click.native.prevent="handleSave(2)"
              >其他领料</el-button
            >
          </el-col> -->
        </el-row>
      </el-form>
    </div>
    <rintLLT :product-from="prinftMass" />
    <div class="case">
      <na-table
        :datas.sync="tableData"
        :searchObj.sync="search"
        @updateDatas="getAllMaterils"
        @newAdd="newAddClick"
      >
      </na-table>
      <SelectSCorder
        :per-visible.sync="showOrder"
        @current="selectCurrentRow"
      />
    </div>
    <!-- 人员寻找弹框   -->
    <per-redio-dialog
      :per-visible.sync="isperShow"
      @getEmployee="getEmployee"
    />
    <el-dialog
      :title="tname"
      :visible.sync="isAddProduct"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
      @open="openCp"
    >
      <div class="dialogDody">
        <div class="addWuliaoBox">
          <el-form
            ref="ProductForm"
            :model="ProductForm"
            :rules="rules"
            label-width="110px"
            label-position="left"
            class="dialogForm dialogInlineForm"
            :disabled="canDiable"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="领料单号" prop="getMaterialBillNo">
                  <el-input
                    :value="ProductForm.getMaterialBillNo || '系统自动生成'"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="创建人员" prop="createPersonName">
                  <el-input
                    :value="opsid != 1 ? ProductForm.createPersonName : name"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="创建日期" prop="createDate">
                  <el-input
                    :value="ProductForm.createDate || getDate()"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowInfo">
              <el-col :span="8">
                <el-form-item label="订单单号" prop="saleOrderNo">
                  <el-input
                    v-model="ProductForm.saleOrderGroupNumber"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="协议书号" prop="xieYiShuHao">
                  <el-input
                    v-model="ProductForm.xieYiShuHao"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生产单号" prop="produceTaskBillNo">
                  <el-input
                    v-model="ProductForm.produceTaskBillNo"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowInfo">
              <el-col :span="8">
                <el-form-item label="产品名称" prop="orderProductName">
                  <el-input
                    v-model="ProductForm.orderProductName"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="版面" prop="printingSurface">
                  <el-input
                    v-model="ProductForm.printingSurface"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="版本" prop="productVersion">
                  <el-input
                    v-model="ProductForm.productVersion"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" v-if="isShowInfo">
                <el-form-item label="客户单号" prop="customerBillNo">
                  <el-input
                    v-model="ProductForm.customerBillNo"
                    size="mini"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="领料类型" prop="getMaterialType">
                  <el-select
                    filterable
                    v-model="ProductForm.getMaterialType"
                    placeholder="领料类型"
                    @change="materialTypeChange"
                    size="mini"
                  >
                    <el-option
                      v-for="item in purchaseTypes"
                      :key="item.dicValueCode"
                      :label="item.dicValueDesc"
                      :value="item.dicValueCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="领料备注" class="inlineText mt8">
              <el-input
                v-model="ProductForm.getMaterialRemark"
                type="textarea"
                :rows="3"
                placeholder="领料备注"
                size="mini"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="作废原因"
              class="inlineText mt16"
              v-if="ProductForm.cancelReason"
            >
              <el-input
                v-model="ProductForm.cancelReason"
                type="textarea"
                :rows="3"
                disabled
                placeholder="领料备注"
                size="mini"
                clearable
              />
            </el-form-item>
          </el-form>
          <div class="tableBox">
            <div class="tt flex flex_between">
              <span class="fw">领料明细</span>
            </div>
            <div ref="bigdialogTable" class="bigdialogTbCon">
              <el-table
                :data="ProductForm.mxDataList"
                :row-key="(row) => row.rowKey"
                v-if="isAddProduct"
                ref="detailTable"
                border
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column
                  prop="specificationCode"
                  width="150"
                  align="center"
                  label="规格编号"
                >
                  <template slot-scope="scope">
                    {{ scope.row.specificationCode || "--" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="materialType"
                  width="100"
                  align="center"
                  label="物料类型"
                >
                  <template slot-scope="scope">
                    {{ scope.row.categoryName || "--" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="school"
                  width="150"
                  align="center"
                  label="供应商"
                >
                  <template slot-scope="scope">
                    <el-select
                      filterable
                      v-model="scope.row.supplierCode"
                      placeholder="请选择供应商"
                      :disabled="canDiable"
                      size="small"
                      @change="supplierChange(scope.row, $event)"
                    >
                      <el-option
                        :key="index"
                        :label="item.supplierName"
                        :value="item.supplierCode"
                        v-for="(item, index) in allSupliers"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="school"
                  width="150"
                  align="center"
                  label="物料名称"
                >
                  <template slot-scope="scope">
                    <el-select
                      filterable
                      v-model="scope.row.goodsCode"
                      placeholder="请选择物料"
                      size="small"
                      :disabled="canDiable"
                      @change="
                        handleMaterialNameChange(
                          scope.row,
                          scope.$index,
                          $event
                        )
                      "
                    >
                      <el-option
                        :label="item.goodsName"
                        :value="item.goodsCode"
                        v-for="(item, index) in scope.row.materialList"
                        :key="index"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="specificationCode"
                  width="150"
                  align="center"
                  label="规格型号"
                >
                  <template slot-scope="scope">
                    <el-select
                      filterable
                      :disabled="canDiable"
                      v-model="scope.row.specificationCode"
                      @change="
                        handleSpecificationChange(scope.row, scope.$index)
                      "
                      placeholder="请选择规格型号"
                      size="small"
                    >
                      <el-option
                        :label="item.specificationName"
                        :value="item.specificationCode"
                        v-for="(item, index) in scope.row
                          .goodsSpecificationList"
                        :key="index"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="machineCode"
                  width="150"
                  align="center"
                  label="机台名称"
                >
                  <template scope="{row}">
                    <el-select
                      filterable
                      v-model="row.machineCode"
                      :disabled="canDiable"
                      placeholder="请选择"
                      size="small"
                    >
                      <el-option
                        v-for="item in allMaterielClass"
                        :key="item.machineCode"
                        :label="item.machineName"
                        :value="item.machineCode"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column
                  v-if="opsid != 2"
                  prop="stockQuantity"
                  width="100"
                  align="center"
                  label="库存数量"
                >
                </el-table-column>
                <el-table-column
                  prop="inStockQuantity"
                  width="100"
                  align="center"
                  label="申请数量"
                >
                  <template slot-scope="{ row }">
                    <el-input
                      :disabled="canDiable"
                      v-model="row.applyGetQuantity"
                      placeholder="请输入"
                      size="mini"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="goodsUnitName"
                  width="150"
                  align="center"
                  label="使用单位"
                >
                </el-table-column>
                <el-table-column
                  prop="getMaterialRemark"
                  align="center"
                  label="备注"
                >
                  <template slot-scope="{ row }">
                    <el-input
                      :disabled="canDiable"
                      v-model="row.getMaterialRemark"
                      placeholder="请输入"
                      size="mini"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="100px"
                  fixed="right"
                  align="center"
                  v-if="!canDiable"
                >
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      v-if="
                        ProductForm.mxDataList.length > 1 &&
                        ProductForm.mxDataList.length - 1 != scope.$index
                      "
                      @click="handleDeleteRow(scope.row, scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button v-if="opsid === 2" size="mini" @click="printLL"
          >打印领料单</el-button
        > -->
        <el-button size="mini" @click="isAddProduct = false">取 消</el-button>
        <!-- 新增       -->
        <el-button
          v-if="opsid !== 2"
          :loading="addProductLoading"
          :disabled="addProductLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="savell"
          >{{ btm }}</el-button
        >
        <el-button
          v-if="opsid !== 2 && opsid !== 3"
          :loading="addProductLoading"
          :disabled="addProductLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="savell('confirm')"
          >保存并确认</el-button
        >
      </div>
    </el-dialog>
    <SelectMateriaList
      ref="materiaList"
      :per-visible.sync="isSemidialog"
      :select-list="list"
      @getMateriListData="refuseListsAll"
    />
    <!-- 原因   -->
    <el-dialog
      title="作废原因"
      :visible.sync="isNopassshow"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="40%"
      @close="closePassDialog"
    >
      <div class="dialogDody">
        <el-form ref="passForm" :model="passForm" class="dialogForm">
          <el-form-item class="mt12">
            <el-input
              v-model="passForm.cancelReason"
              prop="cancelReason"
              type="textarea"
              placeholder="请输入内容"
              :autosize="{ minRows: 6 }"
              size="mini"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isNopassshow = false">取 消</el-button>
        <el-button
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="passSave"
          >提交</el-button
        >
      </span>
    </el-dialog>

    <!-- 切换账号 -->
    <el-dialog
      title="快速登录"
      :visible.sync="loginModel"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog "
      width="25%"
    >
      <div class="p16 pt0">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          hide-required-asterisk
          label-width="auto"
          class="dialogForm dialogInlineForm"
          label-position="top"
        >
          <el-row>
            <el-col>
              <el-form-item label="登录账号" prop="loginAccount">
                <el-input
                  v-model="loginForm.loginAccount"
                  size="small"
                  placeholder="输入登录账号"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="登录密码" prop="loginPassWord">
                <el-input
                  v-model="loginForm.loginPassWord"
                  size="small"
                  show-password
                  placeholder="输入登录密码"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-button
                type="primary"
                size="small"
                style="width: 100%; margin-top: 10px"
                @click.native.prevent="handleLogin"
                >确认登录</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { arraySort, filterSpecifications } from "@/utils";
import HeadSeting from "@/components/HeadSeting";
import Pagination from "@/components/Pagination";
import perRedioDialog from "@/components/perDialogRedio";
import selectProductOrder from "@/components/selectProductOrder";
import SelectSCorder from "@/components/selectSCorder";
import SelectMateriaList from "@/components/selectMaterial";
import rintLLT from "./productionPicker/printLLT.vue";
import screec from "@/components/screen";
import naTable from "@/components/naTable";
import { mapGetters } from "vuex";

export default {
  name: "Materiel",
  components: {
    Pagination,
    HeadSeting,
    perRedioDialog,
    SelectMateriaList,
    selectProductOrder,
    SelectSCorder,
    rintLLT,
    screec,
    naTable,
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不正确"));
      } else {
        callback();
      }
    };
    return {
      isShow: true,
      isShowInfo: true,
      ops: "add", // 操作、新建，修改，查看
      opsid: 1, // 3 确定 1 新建， 4 修改， 2 查看
      list: [],
      tableHeight: null, // 表格最大高度
      showOrder: false,
      cancelForm: {
        purchaseID: 0,
        cancelReason: "",
        purchaseOrderState: 0,
      },
      reasonVisible: false,
      cancelRules: {
        cancelReason: [
          {
            required: true,
            message: "请填写原因",
            trigger: ["change", "blur"],
          },
        ],
      },
      isSeeMaterriel: false, // 查看弹框是否打开
      addLableLoading: false,
      isAddMaterriel: false, // 新建弹框是否打开
      addMaterrielLoading: false, // 新建保存加载
      searchLoading: false, // 搜索加载效果
      allMaterirls: [], // 全部数据列表
      allMaterielClass: [], //机台
      colorState: null,
      addLoading: false,
      selectRow: null,
      isNopassshow: false,
      disabled: false,
      tableData: {
        headId: "head", //表头列显隐组件所需ID-避免多个页面id重复问题
        tableId: "getMaterialID", //表格列表key,也就是一条数据的唯一标识
        senior: false, //高级搜索是否显示
        addPermission: "", //新建按钮权限
        addTitle: "无单据领料", //新建按钮名称-为''则不显示，为undefine则为新建
        disableWord: "", //是否禁用显示的字段
        disableStatus: "", //判断未禁用的状态值
        //表格按钮
        operationBtn: [
          {
            title: "查看",
            methodsName: "handleClick",
          },
          {
            title: "编辑",
            methodsName: "handleUpdata",
            permission: "MenuCode2-3-1",
            hideCondition: {
              //按钮显隐条件
              prop: "getMaterialBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用
                0,
              ],
            },
          },
          {
            title: "确定",
            methodsName: "handleConfirm",
            permission: "MenuCode2-3-2",
            hideCondition: {
              //按钮显隐条件
              prop: "getMaterialBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用
                0,
              ],
            },
          },
          {
            title: "撤回",
            methodsName: "handleWithdraw",
            hideCondition: {
              //按钮显隐条件
              prop: "isWithdraw", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用-值必须跟状态的类型保持一致
                1,
              ],
            },
          },
          {
            title: "作废",
            methodsName: "handleDone",
            permission: "MenuCode2-3-3",
            hideCondition: {
              //按钮显隐条件
              prop: "getMaterialBillState", //控制显隐的状态字段
              show: [
                //有哪些状态可以使用
                0,
              ],
            },
          },
          {
            title: "打印领料单",
            methodsName: "handleDownload",
          },
          // {
          //   title: "复制",
          //   methodsName: "handleCopy",
          //   permission: "MenuCode2-3-1-6",
          //   hideCondition: {
          //     //按钮显隐条件
          //     prop: "getMaterialBillState", //控制显隐的状态字段
          //     show: [
          //       //有哪些状态可以使用
          //       2,
          //     ],
          //   },
          // },
          // {
          //   title: "删除",
          //   methodsName: "handleDelete",
          //   permission: "MenuCode2-3-1-5",
          //   hideCondition: {
          //     //按钮显隐条件
          //     prop: "getMaterialBillState", //控制显隐的状态字段
          //     show: [
          //       //有哪些状态可以使用
          //       0,
          //     ],
          //   },
          // },
        ],
        //表格内容
        tbody: [],
        //表格表头
        thead: [],
      },

      equipmentList: [],
      passForm: {
        cancelReason: "",
      },
      prinftMass: {},

      form: {
        produceTaskBillNo: "", //订单编号
        deviceCraftCode: "", //机台工艺编号
        produceTaskBillNoFl: "",
        produceTaskBillNoLl: "",
      },

      loginForm: {
        loginAccount: "", //账号
        loginPassWord: "", //密码
      },
      loginModel: false,

      loginRules: {
        loginAccount: [
          {
            required: true,
            trigger: "blur",
            message: "请输入账号",
          },
        ],
        loginPassWord: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword,
          },
        ],
      },
      rowData: "",
      // 表格操作
      ProductForm: {
        getMaterialType: '',
        getMaterialPersonName: "",
        equipmentNo: "",
        outStockState: 0,
        mxDataList: [],
      },
      // 搜索条件
      search: {
        QueryDataBaseFiled: "",
        pageIndex: 1,
        pageSize: 30,
        likeWords: "",
      },
      total: 0, // 总条数
      tableHead: [], // 表格表头
      addProductLoading: false,
      isAddProduct: false,
      isperShow: false,
      isSemidialog: false,
      multipleSelection: null,
      allSupliers: [],
      purchaseTypes: [
        {
          dicValueID: 0,
          dicValueDesc: "生产领料",
          dicValueCode: 1,
        },
        // {
        //   dicValueID: 1,
        //   dicValueDesc: "生产补料",
        //   dicValueCode: 2,
        // },
        {
          dicValueID: 2,
          dicValueDesc: "辅料领料",
          dicValueCode: 3,
        },
        {
          dicValueID: 3,
          dicValueDesc: "生产追料",
          dicValueCode: 4,
        },
        {
          dicValueID: 4,
          dicValueDesc: "调机用料",
          dicValueCode: 5,
        },
        {
          dicValueID: 5,
          dicValueDesc: "油墨领料",
          dicValueCode: 6,
        },
      ],
      canDiable: false,
      resProductMaterialList: [],
      rules: {
        getMaterialType: [
          { required: true, message: "请选择领料类型", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["name", "userInfo"]),
    btm() {
      if (this.opsid === 3) {
        return "确认";
      } else {
        return "仅保存";
      }
    },
    tname() {
      if (this.opsid === 1) {
        return "新建生产领料单";
      } else if (this.opsid === 2) {
        return "查看生产领料单";
      } else if (this.opsid === 3) {
        return "确定生产领料单";
      } else if (this.opsid === 4) {
        return "修改生产领料单";
      } else {
        return "复制生产领料单";
      }
    },
  },
  created() {
    // this.openADD = this.openADD ? this.openADD : this.$route.query.openADD

    //  所有列表数据
    this.getAllMaterils();
    // 表格得表头
    this.getTableHead();

    //获取供应商
    // this.getSupplier();

    //获取机台
    this.getMaterielClass();

    if (this.$route.query.openADD) {
      const row = this.$route.query.item;
      this.ops = "add";
      this.isAddProduct = true;
      this.ProductForm.produceTaskBillNo = row.produceTaskBillNo;
      this.ProductForm.getMaterialPersonName = row.createPersonName;
      this.ProductForm.saleOrderNo = row.saleOrderNo;
      this.openCp();
    }
  },
  mounted() {},
  updated() {},
  methods: {
    printLL() {
      const { mxDataList, ...basedata } = this.ProductForm;
      this.prinftMass = {
        mxDataList: basedata.getProduceMaterialMxList,
        basedata: basedata,
      };
      var printHtml = document.getElementById("print-iframe-ll").innerHTML;
      var wind = window.open(
        "",
        "newwindow",
        " top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no"
      );
      wind.document.body.innerHTML = printHtml;
      wind.print();
    },
    closePassDialog() {
      this.passForm.cancelReason = "";
      this.selectRow = null;
    },

    // 获取所有设备
    getMaterielClass() {
      this.$api.product
        .GetMatchProductDevices({
          likeWords: "",
          machineState: 1,
        })
        .then((res) => {
          this.allMaterielClass = res;
        });
    },

    // 获取供应商
    getSupplier(list) {
      this.$api.mater.GetAllSuppliers().then((res) => {
        this.allSupliers = res
        // this.allSupliers = this.filterSupplier(res, list);
      });
    },

    //登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              location.reload();
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },

    getDate() {
      return this.dayjs().format("YYYY-MM-DD");
    },

    //领料类型选择事件
    materialTypeChange(e) {
      if (e == 3 || e == 6) {
        this.ProductForm.mxDataList = [];
        this.resProductMaterialList = [];
        this.ProductForm.mxDataList.push({
          produceMaterialNo: "",
          stockGoodsCode: "",
          applyGetQuantity: 0,
          getMaterialRemark: "",
          machineCode: "",
          goodsCode: "",
          supplierCode: "",
          materialList: [],
          rowKey: Date.now(),
          specificationCode: "",
        });
      } else {
        this.resProductMaterialList = this.resProductMaterialListCopy;
        if (this.opsid == 1) {
          if (this.isShowInfo) {
            this.handleSave();
          }
        } else {
          if (this.isShowInfo) {
            this.getDetail(this.rowData);
          }
        }
      }
      this.getSupplier([]);
    },

    //复制明细
    handleCopyRow(row, index) {
      let copyData = JSON.parse(JSON.stringify(row));
      copyData.rowKey = Date.now();
      this.ProductForm.mxDataList.splice(
        index,
        0,
        JSON.parse(JSON.stringify(copyData))
      );
    },

    //过滤供应商
    filterSupplier(allSupliers, productMaterialList) {
      if (!productMaterialList || productMaterialList.length <= 0) {
        return allSupliers;
      }
      let arr = [];
      allSupliers.forEach((item, index) => {
        productMaterialList.forEach((x, i) => {
          if (item.supplierCode == x.supplierCode) {
            arr.push(item);
          }
        });
      });
      return arr;
    },

    //过滤物料
    filterMaterialFun(MaterialList, productMaterialList) {
      if (!productMaterialList || productMaterialList.length <= 0) {
        return MaterialList;
      }
      let arr = [];
      MaterialList.forEach((item, index) => {
        productMaterialList.forEach((x, j) => {
          if (item.goodsCode == x.stockGoodsCode) {
            arr.push(item);
          }
        });
      });
      return arr;
    },

    //过滤规格
    filterSpecificationFun(SpecificationList, productMaterialList) {
      return  SpecificationList
      /*if (!productMaterialList || productMaterialList.length <= 0) {
        return SpecificationList;
      }
      let arr = [];
      SpecificationList.forEach((item, index) => {
        productMaterialList.forEach((x, j) => {
          if (item.specificationCode == x.specification) {
            arr.push(item);
          }
        });
      });
      return arr;*/
    },

    //删除明细
    handleDeleteRow(row, index) {
      this.ProductForm.mxDataList.splice(index, 1);
    },

    //撤回
    handleWithdraw(row){
      const parmas = {
        code: row.getMaterialBillNo,
      };
      this.$confirm("是否确定撤回该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product.RevokeGetProduceMaterialBill(parmas).then(() => {
          this.getAllMaterils();
          this.$message({
            message: "撤回成功",
            type: "success",
          });
        });
      });
    },

    //下载领料单
    handleDownload(row) {
      let code;
      if (row.getMaterialType == 4) {
        code = "MBLX0014";
      } else {
        code = "MBLX0005";
      }
      let parmas = {
        templateTypeCode: code, //	模板类型编号
        condition: {
          GetMaterialBillNo: row.getMaterialBillNo,
        }, //查询条件
      };
      this.$api.system.DownLoadTemplate(parmas).then((res) => {
        window.open(res);
      });
    },

    // 新建点击事件
    newAddClick() {
      this.ops = "add";
      this.isShowInfo = false;
      this.opsid = 1;
      this.isAddProduct = true;
      this.canDiable = false;
      this.getSupplier([]);
      this.ProductForm.mxDataList.push({
        produceMaterialNo: "",
        stockGoodsCode: "",
        applyGetQuantity: 0,
        getMaterialRemark: "",
        machineCode: "",
        goodsCode: "",
        supplierCode: "",
        materialList: [],
        rowKey: Date.now(),
        specificationCode: "",
      });
    },

    //点击确定
    handleSave() {
      this.form.produceTaskBillNo = JSON.parse(
        JSON.stringify(this.form.produceTaskBillNoLl)
      );
      this.$refs.materForm.validate((valid) => {
        if (valid) {
          this.$api.product
            .GetProduceTaskBillDetail({
              produceTaskBillNo: this.form.produceTaskBillNo,
            })
            .then((res) => {
              if (res.baseData.produceBillState == 0) {
                this.$message.error("生产单状态不是已确认，不能创建领料单！");
                return;
              }
              this.isShowInfo = true;
              this.ops = "add";
              this.opsid = 1;
              this.isAddProduct = true;
              this.canDiable = false;
              this.ProductForm.saleOrderGroupNumber =
                res.orderBaseData.saleOrderGroupNumber;
              this.ProductForm.saleOrderNo = res.orderBaseData.orderNo;
              this.ProductForm.productCode = res.baseData.productCode;
              this.ProductForm.produceTaskBillNo =
                res.baseData.produceTaskBillNo;
              this.ProductForm.customerBillNo =
                res.orderBaseData.customerBillNo;
              this.ProductForm.orderProductName =
                res.productInfo.baseData.productName;
              this.ProductForm.printingSurface =
                res.productInfo.baseData.productLayout;
              this.ProductForm.productVersion =
                "V" +
                res.productInfo.baseData.newVersion +
                "." +
                res.productInfo.baseData.updateVersion;
              this.ProductForm.xieYiShuHao = res.orderBaseData.xieYiShuHao;
              this.ProductForm.mxDataList = res.produceMaterialList;
              this.resProductMaterialList = res.productInfo.productMaterialList;
              this.resProductMaterialListCopy =
                res.productInfo.productMaterialList;
              this.getSupplier(res.productInfo.productMaterialList);
              if (this.ProductForm.mxDataList.length) {
                this.ProductForm.mxDataList.forEach((item,index) => {
                  this.$api.mater
                    .GetGoodsSpecificationBySupplierCode({
                      queryBy: 0,
                      queryValue: item.supplierCode,
                    })
                    .then((data) => {
                      this.$set(
                        item,
                        "materialList",
                          data
                          
                      );
                      item.materialList.forEach((k) => {
                        if (item.goodsCode == k.goodsCode) {
                          this.$set(
                            item,
                            "goodsSpecificationList",
                              k.goodsSpecificationList,
                          );
                        }
                      });
                    });
                  item.machineCode = item.equipmentNo;
                  this.$set(
                    item,
                    "applyGetQuantity",
                    res.baseData.plannedMaterials
                  );
                  item.rowKey = index
                  // item.applyGetQuantity = res.baseData.plannedMaterials
                });
              }
              this.ProductForm.mxDataList.push({
                produceMaterialNo: "",
                stockGoodsCode: "",
                applyGetQuantity: 0,
                getMaterialRemark: "",
                machineCode: "",
                goodsCode: "",
                supplierCode: "",
                rowKey: Date.now(),
                materialList: [],
                specificationCode: "",
              });
              console.log(this.ProductForm.mxDataList);
            });
        }
      });
    },

    //规格型号选择事件
    handleSpecificationChange(row, index) {
      this.ProductForm.mxDataList.forEach((item) => {
        if (
          item.goodsSpecificationList &&
          item.goodsSpecificationList.length > 0
        ) {
          item.goodsSpecificationList.forEach((x) => {
            if (item.specificationCode == x.specificationCode) {
              item.productionBatchList = x.productionBatchList;
              item.stockQuantity = x.stockQuantity;
              item.goodsPrice = x.goodsPrice;
              item.stockGoodsCode = x.specificationCode;
            }
          });
        }
      });
      this.$forceUpdate();
    },

    handleClick(row) {
      this.opsid = 2;
      this.canDiable = true;
      this.getDetail(row);
    },

    handleConfirm(row) {
      this.opsid = 3;
      this.canDiable = true;
      this.getDetail(row);
    },
    handleDone(row) {
      this.selectRow = row;
      this.isNopassshow = true;
    },
    handleCopy(row) {
      this.opsid = 5;
      this.canDiable = false;
      // this.getDetail(row)
      this.openCp();

      const _data = {
        getMaterialID: row.getMaterialID,
        getMaterialBillNo: row.getMaterialBillNo,
      };
      this.$api.product.GetProduceMaterialBillDetail(_data).then((res) => {
        this.equipmentList.push({
          equipmentName: res.equipmentName,
          equipmentNo: res.equipmentNo,
        });
        delete res.baseData.getMaterialID;
        delete res.baseData.getMaterialBillNo;
        this.ProductForm = res.baseData;
        this.ProductForm.mxDataList = res.mxDataList;

        // this.ProductForm = res
        this.isAddProduct = true;
      });
    },
    handleUpdata(row) {
      this.opsid = 4;
      this.canDiable = false;
      this.rowData = row;
      this.getDetail(row);
    },
    passSave() {
      const _data = {
        getMaterialID: this.selectRow.getMaterialID,
        cancelReason: this.passForm.cancelReason,
      };
      this.$api.product
        .CancelGetProduceMaterialBill(_data)
        .then(() => {
          this.getAllMaterils();
          this.isNopassshow = false;
          this.addLoading = false;
          this.$message({
            message: "作废成功",
            type: "success",
          });
        })
        .catch(() => {});
    },
    handleDelete(row) {
      const _data = {
        getMaterialID: row.getMaterialID,
      };
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product
          .DeleteGetProduceMaterialBill(_data)
          .then(() => {
            this.getAllMaterils();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          })
          .catch(() => {});
      });
    },

    getDetail(row) {
      const _data = {
        getMaterialID: row.getMaterialID,
        getMaterialBillNo: row.getMaterialBillNo,
      };
      this.$api.product.GetProduceMaterialBillDetail(_data).then((res) => {
        this.equipmentList.push({
          equipmentName: res.equipmentName,
          equipmentNo: res.equipmentNo,
        });
        res.baseData.orderProductName = res.baseData.productName;
        this.ProductForm = res.baseData;
        this.ProductForm.saleOrderGroupNumber = res.baseData.saleOrderNo;
        this.resProductMaterialList = res.baseData.productMaterialList;
        this.resProductMaterialListCopy = res.baseData.productMaterialList;
        this.getSupplier(res.baseData.productMaterialList);
        res.baseData.getProduceMaterialMxList.forEach((item, index) => {
            this.$api.mater
              .GetGoodsSpecificationBySupplierCode({
                queryBy: 0,
                queryValue: item.supplierCode,
              })
              .then((data) => {
                this.$set(
                  item,
                  "materialList",
                  data
                );
                item.materialList.forEach((k) => {
                  if (item.goodsCode == k.goodsCode) {
                    this.$set(
                      item,
                      "goodsSpecificationList",
                        k.goodsSpecificationList,
                    );
                    item.goodsType = k.goodsType;
                  item.priceUnit = k.goodsUnit;
                  }
                });
              });

          item.equipmentName = item.machineName;
          item.categoryName = item.goodsCategoryName;
          item.rowKey = index
        });
        this.$set(
          this.ProductForm,
          "mxDataList",
          res.baseData.getProduceMaterialMxList
        );
        console.log(this.ProductForm)
        if (this.opsid != 2 && this.opsid != 3) {
          this.ProductForm.mxDataList.push({
            produceMaterialNo: "",
            stockGoodsCode: "",
            applyGetQuantity: 0,
            getMaterialRemark: "",
            machineCode: "",
            goodsCode: "",
            supplierCode: "",
            materialList: [],
            specificationCode: "",
            rowKey: Date.now()
          });
        }
        console.log(this.ProductForm.mxDataList)
        this.prinftMass = res;
        this.isAddProduct = true;
      });
    },

    selectCurrentRow(row) {
      this.ops = "add";
      this.isAddProduct = true;
      this.ProductForm.produceTaskBillNo = row.produceTaskBillNo;
      this.ProductForm.saleOrderNo = row.saleOrderNo;

      this.ProductForm.productCode = row.productCode;
      this.ProductForm.customerBillNo = row.customerBillNo;
      this.ProductForm.orderProductName = row.orderProductName;
      this.ProductForm.productVersion =
        row.printingSurface + row.orderProductVersion;
      this.ProductForm.xieYiShuHao = row.xieYiShuHao;
    },
    openCp() {
      const _data = {
        produceTaskBillNo: this.ProductForm.produceTaskBillNo,
        likeWords: "",
      };
      this.$api.product.GetProduceTaskEquipmentList(_data).then((res) => {
        this.equipmentList = res;
        // if (res && res.length) {
        //   this.ProductForm.equipmentNo = res[0].equipmentNo
        // }
      });
    },
    savell(type) {

      if (this.opsid === 3) {
        const _data3 = {
          getMaterialID: this.ProductForm.getMaterialID,
        };
        this.$api.product
          .SureGetProduceMaterialBill(_data3)
          .then(() => {
            let code;
            if (this.ProductForm.getMaterialType == 4) {
              code = "MBLX0014";
            } else {
              code = "MBLX0005";
            }
            let parmas = {
              templateTypeCode: code, //	模板类型编号
              condition: {
                GetMaterialBillNo: this.ProductForm.getMaterialBillNo,
              }, //查询条件
            };
            this.$api.system.DownLoadTemplate(parmas).then((res) => {
              window.open(res);
            });
            this.addProductLoading = false;
            this.isAddProduct = false;
            this.getAllMaterils();
            this.$message({
              message: "确认成功",
              type: "success",
            });
          })
          .catch(() => {
            this.addProductLoading = false;
          });
      } else if (this.opsid === 4) {
        this.$refs.ProductForm.validate((valid) => {
          if (valid) {
            let parmas;
            let state = true;
            if (this.ProductForm.mxDataList.length < 2) {
              this.$message.warning("请选择领料明细");
              return;
            }
            let arr = JSON.parse(JSON.stringify(this.ProductForm.mxDataList));
            arr.pop();
            arr.forEach((item) => {
              if (!item.goodsCode) {
                state = false;
              }
            });
            if (!state) {
              this.message.warning("请选择物料名称");
              return;
            }
            this.ProductForm.mxDataList = JSON.parse(JSON.stringify(arr));
            console.log(this.ProductForm.mxDataList);
            parmas = this.ProductForm;
            this.addProductLoading = true;
            if (type === "confirm") {
              this.$api.product
                .UpdateGetProduceMaterialBill(parmas)
                .then(() => {
                  const _data3 = {
                    getMaterialID: this.ProductForm.getMaterialID,
                  };
                  this.$api.product
                    .SureGetProduceMaterialBill(_data3)
                    .then(() => {
                      let code;
                      if (this.ProductForm.getMaterialType == 4) {
                        code = "MBLX0014";
                      } else {
                        code = "MBLX0005";
                      }
                      let parmas = {
                        templateTypeCode: code, //	模板类型编号
                        condition: {
                          GetMaterialBillNo: this.ProductForm.getMaterialBillNo,
                        }, //查询条件
                      };
                      this.$api.system.DownLoadTemplate(parmas).then((res) => {
                        window.open(res);
                      });
                      this.addProductLoading = false;
                      this.isAddProduct = false;
                      this.getAllMaterils();
                      this.$message({
                        message: "确认成功",
                        type: "success",
                      });
                    })
                    .catch(() => {
                      this.addProductLoading = false;
                    });

                  // this.addProductLoading = false;
                  // this.isAddProduct = false;
                  // this.getAllMaterils();
                  // this.$message({
                  //   message: "修改成功",
                  //   type: "success",
                  // });
                })
                .catch(() => {
                  this.addProductLoading = false;
                });
            } else {
              this.$api.product
                .UpdateGetProduceMaterialBill(parmas)
                .then(() => {
                  this.addProductLoading = false;
                  this.isAddProduct = false;
                  this.getAllMaterils();
                  this.$message({
                    message: "修改成功",
                    type: "success",
                  });
                })
                .catch(() => {
                  this.addProductLoading = false;
                });
            }
          }
        });
      } else {
        this.$refs.ProductForm.validate((valid) => {
          if (valid) {
            let parmas;
            let state = true;
            if (this.ProductForm.mxDataList.length < 2) {
              this.$message.warning("请选择领料明细");
              return;
            }
            let arr = JSON.parse(JSON.stringify(this.ProductForm.mxDataList));
            arr.pop();
            arr.forEach((item) => {
              if (!item.goodsCode) {
                state = false;
              }
            });
            if (!state) {
              this.message.warning("请选择物料名称");
              return;
            }
            this.ProductForm.mxDataList = JSON.parse(JSON.stringify(arr));
            parmas = this.ProductForm;
            this.addProductLoading = true;

            if (type === "confirm") {
              this.$api.product
                .CreateGetProduceMaterialBill(parmas)
                .then((res) => {
                  const _data3 = {
                    getMaterialID: res.getMaterialID,
                  };
                  this.$api.product
                    .SureGetProduceMaterialBill(_data3)
                    .then(() => {
                      let code;
                      if (this.ProductForm.getMaterialType == 4) {
                        code = "MBLX0014";
                      } else {
                        code = "MBLX0005";
                      }
                      let parmas = {
                        templateTypeCode: code, //	模板类型编号
                        condition: {
                          GetMaterialBillNo: res.getMaterialBillNo,
                        }, //查询条件
                      };
                      this.$api.system.DownLoadTemplate(parmas).then((ress) => {
                        window.open(ress);
                      });
                      this.addProductLoading = false;
                      this.isAddProduct = false;
                      this.getAllMaterils();
                      this.$message({
                        message: "确认成功",
                        type: "success",
                      });
                    })
                    .catch(() => {
                      this.addProductLoading = false;
                    });
                  // this.addProductLoading = false;
                  // this.isAddProduct = false;
                  // this.getAllMaterils();
                  // this.$message({
                  //   message: "保存成功",
                  //   type: "success",
                  // });
                })
                .catch(() => {
                  this.addProductLoading = false;
                });
            } else {
              this.$api.product
                .CreateGetProduceMaterialBill(parmas)
                .then((res) => {
                  this.addProductLoading = false;
                  this.isAddProduct = false;
                  this.getAllMaterils();
                  this.$message({
                    message: "保存成功",
                    type: "success",
                  });
                })
                .catch(() => {
                  this.addProductLoading = false;
                });
            }
          }
        });
      }
    },

    // 得到申请人员
    getEmployee(val) {
      this.ProductForm.getMaterialPersonName = val.employeeName;
      this.ProductForm.getMaterialPerson = val.employeeCode;
    },

    //供应商选择事件
    supplierChange(row, val) {
      row.goodsCode = "";
      row.specificationCode = "";
      row.productionBatchCode = "";
      row.materialList = [];
      row.goodsSpecificationList = [];
      row.goodsType = "";

      this.$api.mater
        .GetGoodsSpecificationBySupplierCode({
          queryBy: 0,
          queryValue: val,
        })
        .then((res) => {
          this.$set(
            row,
            "materialList",
            res
          );
          // row.materialList = res;
          // console.log(this.ProductForm.mxDataList)
        });

      this.$forceUpdate();
    },

    //物料下拉选择事件
    handleMaterialNameChange(row, index, e) {
      if (index == this.ProductForm.mxDataList.length - 1) {
        this.ProductForm.mxDataList.push({
          produceMaterialNo: "",
          stockGoodsCode: "",
          applyGetQuantity: 0,
          getMaterialRemark: "",
          machineCode: "",
          goodsCode: "",
          supplierCode: "",
          specificationCode: "",
          materialList: [],
          rowKey: Date.now(),
        });
      }
      // row.stockGoodsCode = e;
      row.specificationCode = "";
      row.materialList.forEach((item, i) => {
        if (item.goodsCode == e) {
          row.categoryName = item.goodsType;
          row.materialName = item.goodsName;
          this.$set(row, "goodsSpecificationList", item.goodsSpecificationList);
          row.goodsUnitName = item.goodsUnit;
          // row.goodsType = item.goodsType;
          // row.priceUnit = item.priceUnit;
        }
      });
    },

    closeSemiDialog() {
      this.isSemidialog = false;
    },
    MarterdialogShow() {},
    handleSelectionChange(val) {
      val.forEach((res) => {
        res.goodsCategoryName = res.categoryName;
        res.planUseQuantity = res.planMaterialQuantity;
      });
      this.multipleSelection = val;
    },
    // 选择材料后刷新
    refuseListsAll(selectArr) {
      const array = JSON.parse(JSON.stringify(this.ProductForm.mxDataList));
      const arr = JSON.parse(JSON.stringify(selectArr));
      arr.forEach((item) => {
        item.goodsCategoryName = item.categoryName;
        item.produceMaterialNo = item.goodsCode;
        item.applyGetQuantity = 0;
        item.stockQuantity = item.stockSumQuantity;
        item.getMaterialRemark = "";
      });
      this.ProductForm.mxDataList = arr.reduce((result, item) => {
        const val = result.some(
          ({ stockGoodsCode }) => stockGoodsCode === item.stockGoodsCode
        );
        if (!val) {
          result.push(item);
        }
        return result;
      }, array);
      this.closeSemiDialog();
    },
    // ，清除所有查询条件
    Refresh() {
      this.search = this.$options.data().search;
      this.getAllMaterils();
    },
    // 获取表格表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.producegetmaterialbilllist,
      };
      this.$api.common.getAllTableHead(parmas).then((res) => {
        res.sort(arraySort("columnSort"));
        this.tableData.thead = res;
      });
    },
    // 所有列表数据
    getAllMaterils() {
      const parmas = this.search;
      this.searchLoading = true;
      this.$api.product
        .GetMatchPageProduceMaterialBills(parmas)
        .then((res) => {
          this.allMaterirls = res.list;
          this.tableData.tbody = res.list;
          this.search.total = res.totalCount;
          this.allMaterirls.forEach((item) => {
            item.isWithdraw = 0
            for (let i in item) {
              if (!item[i] && item[i] !== 0) {
                item[i] = "--";
              }
            }
            if (item.getMaterialBillState == 1 && (item.outStockState == 0 || item.outStockState == 3)
            ) {
              item.isWithdraw = 1;
            }
          });
          this.total = res.totalCount;
          this.searchLoading = false;
        })
        .catch(() => {
          this.searchLoading = false;
        });
    },
    // 新建弹框关闭事件
    closeDialog() {
      if (this.$refs.ProductForm) {
        this.$refs.ProductForm.resetFields();
      }
      this.ProductForm = this.$options.data().form;
      this.ProductForm = this.$options.data().ProductForm;
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  height: 100%;
}
.permangeRg {
  border: 1px solid #e6e6e6;
  background: #fff;
  height: 100%;

  .mainTT {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    padding: 18px 16px;
    padding-bottom: 0;
  }
}
.addWuliaoBox {
  padding: 10px 16px;

  .tableBox {
    margin-top: 16px;
    border: 1px solid #e6e6e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    overflow: hidden;

    .tt {
      height: 38px;
      line-height: 38px;
      padding-left: 16px;
      background: #f7f8fa;
      border-radius: 8px 8px 0 0;
    }
  }
}

.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}
</style>
